package com.yinp.proapp.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.yinp.proapp.R;
import com.yinp.proapp.module.wanandroid.bean.WanLoginBean;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import okhttp3.Cookie;

import static android.content.Context.ACTIVITY_SERVICE;

public class AppUtils {
    /**
     * 获取屏幕宽度的px
     *
     * @return
     */
    public static float getWidthPixels() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度的px
     *
     * @return
     */
    public static float getHeightPixels() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static float getDensity() {
        return Resources.getSystem().getDisplayMetrics().density;
    }

    /**
     * 改变状态栏文字颜色为白色和黑色
     *
     * @param isDark
     * @param window
     */
    public static void setStatusBarTextColor(boolean isDark, Window window) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //6.0以上
            View decorView = window.getDecorView();
            int vis;
            if (isDark) {
                vis = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;//黑色
            } else {
                vis = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;//白色
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    public static void setFullScreen(Window window) {
//        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
//        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
//            finish();
//            return;
//        }
        WindowManager.LayoutParams lp = window.getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }
        window.setAttributes(lp);
    }

    public static String getText(String value) {
        return TextUtils.isEmpty(value) ? "" : value;
    }

    /**
     * 获取Decode的中文
     *
     * @param encodeName
     * @return
     */
    public static String getDecodeName(String encodeName) {
        String decodeName = "";
        try {
            decodeName = java.net.URLDecoder.decode(encodeName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return decodeName;
    }

    /**
     * dp转px
     *
     * @return
     */
    public static float dpToPx(float value) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return scale * value + 0.5f;
    }

    public static int dpToPx(int value) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (scale * value + 0.5f);
    }

    /**
     * px转dp
     *
     * @return
     */
    public static float pxToDp(float value) {
        final float scale = Resources.getSystem().getDisplayMetrics().density;
        return value / scale + 0.5f;
    }

    public static boolean isLogin(Context context) {
        SharedPrefsCookiePersistor sharedPrefsCookiePersistor = new SharedPrefsCookiePersistor(context);
        List<Cookie> cookies = sharedPrefsCookiePersistor.loadAll();
        if (cookies != null && cookies.size() > 0) {
            WanLoginBean wanLoginBean = WanLoginBean.getUserInfo(context);
            if (wanLoginBean != null) {
                return !TextUtils.isEmpty(wanLoginBean.getUsername());
            } else {
                return false;
            }
        } else {
            return false;
        }


    }

    /**
     * 获取屏幕宽度
     */

    public static int getWidth() {
        DisplayMetrics metrics;
        metrics = Resources.getSystem().getDisplayMetrics();
        return metrics.widthPixels;
    }

    public static String getValue(String value) {
        return getValue(value, "暂无");
    }

    public static String getValue(String value, String defaultValue) {
        if (TextUtils.isEmpty(value)) {
            return defaultValue;
        } else {
            return value;
        }
    }

    /**
     * 查看sha1值
     */
    public static String sHA1(Context context) {
        try {
            @SuppressLint("PackageManagerGetSignatures") PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuilder hexString = new StringBuilder();
            for (byte b : publicKey) {
                String appendString = Integer.toHexString(0xFF & b)
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断某一个类是否存在任务栈里面
     *
     * @return
     */
    public static boolean isExsitMianActivity(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        ComponentName cmpName = intent.resolveActivity(context.getPackageManager());
        boolean flag = false;
        if (cmpName != null) { // 说明系统中存在这个activity
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = am.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(cmpName)) { // 说明它已经启动了
                    flag = true;
                    break;  //跳出循环，优化效率
                }
            }
        }
        return flag;
    }

    /**
     * ScrollView的情况下，对textView的配置
     */
    public static View.OnTouchListener onTouchListener = new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //父节点不拦截子节点
                v.getParent().requestDisallowInterceptTouchEvent(true);
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                //父节点不拦截子节点
                v.getParent().requestDisallowInterceptTouchEvent(true);
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                //父节点拦截子节点
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        }
    };

    public static View getBlankView(Context mContext) {
        return LayoutInflater.from(mContext).inflate(R.layout.view40, null);
    }

    /**
     * 范围随机数
     * @param min
     * @param max
     * @return
     */
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;
        return randomNum;
    }
}
